﻿// Copyright (c) 2014 Morten Bakkedal
// This code is published under the MIT License.

using System;

using FuncLib.DualFunctions.Expressions;

namespace FuncLib.DualFunctions.Compilation
{
	internal abstract class LoopTerm
	{
		private Expression expression;
	
		public LoopTerm(Expression expression)
		{
			this.expression = expression;
		}

		public abstract void Prepare(FunctionBody body);

		public string GenerateCode()
		{
			string s = GenerateArrayCode();

			if (expression is NumberExpression)
			{
				// Avoid unnecessary multiplication. Zero is already filtered out.
				double c = ((NumberExpression)expression).Value;

				if (c == 1.0)
				{
					return s;
				}

				if (c == -1.0)
				{
					return "-(" + s + ")";
				}
			}

			return expression.GenerateCode() + " * " + s;
		}

		public abstract string GenerateArrayCode();
			
		public Expression Expression
		{
			get
			{
				return expression;
			}
		}
	}
}
